package com.web709.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.web709.common.CustomException;
import com.web709.common.R;
import com.web709.dto.DemandDto;
import com.web709.service.DemandImgService;
import com.web709.service.DemandService;
import com.web709.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/demand")
@Api(tags = "需求管理接口")
@Slf4j
public class DemandController {

    @Autowired
    private DemandService demandService;

    @Autowired
    private DemandImgService demandImgService;

    // 定义一个包装类来接收 JSON 对象
    @Data
    static class ImgRequest {
        private List<String> img;
    }





    // 发表需求（可以上传多张照片，并把图片保存到数据库）
    @PostMapping("/publish")
    @ApiOperation(value = "发表需求", notes = "可以上传多张照片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imgs", value = "图片路径", required = false, dataType = "List<String>"),
            @ApiImplicitParam(name = "demandDto", value = "需求信息", required = true, dataType = "DemandDto"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<String> publishDemand(@RequestBody DemandDto demandDto,
                                   @RequestParam(value = "imgs", required = false) List<String> imgs) {

        // XSS过滤处理
        if (imgs != null && !imgs.isEmpty()) {
            String escapedImgPaths = imgs.stream()
                    .map(path -> path.replace("<", "&lt;")
                            .replace(">", "&gt;")
                            .replace("\"", "&quot;")) // 新增引号转义
                    .collect(Collectors.joining(", "));
            demandDto.setImgPaths(escapedImgPaths);
            log.info("转义后图片路径：{}", escapedImgPaths);
        }

        return demandService.publishDemandWithImgs(demandDto);
    }

    //修改需求
    @PutMapping("/update")
    @ApiOperation(value = "修改需求", notes = "可以上传多张照片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imgs", value = "图片路径", required = false, dataType = "List<String>"),
            @ApiImplicitParam(name = "demandDto", value = "需求信息", required = true, dataType = "DemandDto"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<String> updateDemand(@RequestBody DemandDto demandDto,
                                   @RequestParam(value = "imgs", required = false) List<String> imgs) {

        // XSS过滤处理
        if (imgs != null && !imgs.isEmpty()) {
            String escapedImgPaths = imgs.stream()
                    .map(path -> path.replace("<", "&lt;")
                            .replace(">", "&gt;")
                            .replace("\"", "&quot;")) // 新增引号转义
                    .collect(Collectors.joining(", "));
            demandDto.setImgPaths(escapedImgPaths);
            log.info("转义后图片路径：{}", escapedImgPaths);
        }

        return demandService.updateDemandWithImgs(demandDto);
    }

    // 查询发表的需求以及照片，使用分页返回
    @GetMapping("/query")
    @ApiOperation(value = "查询发表的需求及照片", notes = "使用分页返回")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = false, dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", required = false, dataType = "int", defaultValue = "10"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<Page<DemandDto>> queryDemandsWithImgs(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                   @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        Page<DemandDto> page = new Page<>(pageNum, pageSize);
        return demandService.queryDemandsWithImgs(page);
    }

    // 删除需求以及照片

    @DeleteMapping("/delete/{demandId}")
    @ApiOperation(value = "删除需求以及照片", notes = "删除需求以及照片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "demandId", value = "需求ID", required = true, dataType = "int"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public ResponseEntity<String> deleteDemand(@PathVariable("demandId") int demandId,@RequestHeader(required = false)  String token) {
        return demandService.deleteDemand(demandId);
    }

    //志愿者接待需求
    @PostMapping("/receive")
    @ApiOperation(value = "志愿者接待需求", notes = "根据需求ID和志愿者ID进行接单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "demandId", value = "需求ID", required = true, dataType = "int"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public ResponseEntity<String> receiveDemand(HttpServletRequest request,
                                                @RequestParam("demandId") int demandId) {

        String header = request.getHeader("token");
        Integer volunteerId = JwtUtils.parseJWT(header).get("userId", Integer.class);
        return demandService.receiveDemand(demandId, volunteerId);

    }
}
